package edu.njust.httpmanager.config;

import edu.njust.httpmanager.common.JacksonObjectMapper;
import edu.njust.httpmanager.interceptor.JwtInterceptor;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.List;

@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

    @Resource
    private JwtInterceptor jwtInterceptor;

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建一个新的消息转换器
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 设置对象转换器
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 追加对象转换器
        converters.add(0, messageConverter);    // 第一个参数表示优先级，越小越高
    }

    /**
     * 配置跨域请求
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
        registry.addMapping("/**")  // 允许所有请求url
                .allowedOriginPatterns("http://localhost:5173", "http://192.168.1.102:5173", "http://114.55.94.206")        // 允许请求的进程
                .allowedHeaders("*")    // 允许所有请求头
                .allowedMethods("GET", "POST", "PUT", "DELETE")   // 允许的请求方法
                .allowCredentials(true)     // 允许携带cookie
                .maxAge(3600);  // 跨域验证的有效期：一个小时
    }


    @Override
    protected void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(jwtInterceptor)
                .excludePathPatterns("/login")      // excludePathPatterns：不拦截的路径
                .excludePathPatterns("/sendMsg")
                .excludePathPatterns("/register/*")
                .excludePathPatterns("/api/send/**")
                .addPathPatterns("/**");    // 拦截所有路径
    }
}
